const username = document.getElementById('username');
const password = document.getElementById('password');
const loginBtn = document.getElementById('loginBtn');

function getAllUsers() {
    return JSON.parse(localStorage.getItem('userInfo') || '[]');
}

function setAllUsers(arr) {
        localStorage.setItem('userInfo', JSON.stringify(arr));
    }

function findUser(name) {
    return getAllUsers().find(u => u.username === name);
}


let regName = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,10}$/;
let regPassword = /^[a-zA-Z0-9_]{6,16}$/;

loginBtn.addEventListener('click', function() {
    // 用户名、密码校验
    let name = username.value.trim();
    let pwd = password.value.trim();
    if (!regName.test(name)) {
        alert('用户名格式不正确');
        return;
    }
    if (!regPassword.test(pwd)) {
        alert('密码格式不正确');
        return;
    }
    
    let allUsers = getAllUsers();
    let user = findUser(name);
    // 有账号：比对账号密码
    if (user) {
        if (user.password!== pwd) {
            alert('密码错误');
            return;
        }
        else {
            localStorage.setItem('currentUser', name);
            location.href = 'index.html';
        }
    }
    // 无账号：创建账号后进入详情页
    else {
        user = {
            username: name,
            password: pwd,
            shop : []
        };
        allUsers.push(user);
        setAllUsers(allUsers);
        localStorage.setItem('currentUser', name);
        location.href = 'index.html';
    }
})